package com.ler.action.util;

import com.ler.action.entity.MavenJsonBean;
import com.ler.action.entity.MavenJsonBean.DependencyBean;
import com.ler.action.entity.MavenJsonBean.DependencyBean.ExclusionsBean.ExclusionBean;
import java.util.List;
import org.json.JSONObject;
import org.json.XML;

/**
 * @author lww
 * @date 2020-05-27 15:23
 */
public class XmlParser {

    public static String parseXml(String xmlStr) throws Exception {
        //xml 2 json
        JSONObject jsonObject = XML.toJSONObject(xmlStr);
        MavenJsonBean mavenJsonBean = com.alibaba.fastjson.JSONObject.parseObject(jsonObject.toString(), MavenJsonBean.class);
        StringBuilder sb = new StringBuilder();
        DependencyBean dependency = mavenJsonBean.getDependency();
        sb.append("compile(group: \"")
                .append(dependency.getGroupId())
                .append("\", name: \"")
                .append(dependency.getArtifactId());
        if (dependency.getVersion() == null || dependency.getVersion().isEmpty()) {
            sb.append("\")");
        } else {
            sb.append("\", version: \"")
                    .append(dependency.getVersion())
                    .append("\")");
        }

        if (dependency.getExclusions() != null && dependency.getExclusions().getExclusion() != null && dependency.getExclusions().getExclusion().size() > 0) {
            List<ExclusionBean> exclusion = dependency.getExclusions().getExclusion();
            sb.append("{");
            for (ExclusionBean ex : exclusion) {
                sb.append("\n exclude group: '").append(ex.getGroupId()).append("', module: '").append(ex.getArtifactId()).append("'");
            }
            sb.append("\n }");
        }
        return sb.toString();
    }

}
